package cn.kai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Author: cKnight
 * Date: 2024/6/18
 */
@Slf4j
public class FileCommonUtils {

    /**
     * multipartFile 转 file
     * @param multipartFile
     * @return
     */
    public static File convertToFile(MultipartFile multipartFile)  {
        try {
            return subConvertToFile(multipartFile);
        }catch (IOException ioException){
            log.error("convertToFile异常:",ioException);
            return null;
        }
    }

    private static File subConvertToFile(MultipartFile multipartFile) throws IOException{
        File tempFile = File.createTempFile("temp", null);
        try (InputStream inputStream = multipartFile.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            // JVM 退出时删除
            tempFile.deleteOnExit();
            // 8KB 缓冲区
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    }
}
